/**
 * axios实例封装，在这里加上项目对接口请求的统一处理
 */
import axios from 'axios';
import config from '@/utils/config';
import message from 'ant-design-vue/es/message';
import router from '@/router';

const { apiHost } = config;

const option = {
  baseURL: apiHost,
};

// 创建 axios 实例
const service = axios.create(option);

// http request 拦截器
service.interceptors.request.use(
  (config) => {
    if (localStorage.Authorization) {
      config.headers.Authorization = localStorage.Authorization;
    }
    const requestType = config.requestType || 'json';
    if (requestType === 'upload') {
      config.headers = Object.assign(config.headers || {}, {
        Accept: '*/*',
        'Content-Type': 'multipart/form-data',
      });
      const formData = new FormData();
      Object.keys(config.data).forEach((key) => {
        formData.append(key, config.data[key]);
      });
      config.data = formData;
    }
    return config;
  },
  (err) => Promise.reject(err),
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.headers.authorization || response.headers.Authorization) {
      // $store('user').setToken(response.header.authorization || response.header.Authorization);
      localStorage.setItem('Authorization', response.headers.authorization || response.headers.Authorization);
    }
    
    // 判断处理结果是文件类型时，不对结果集处理，直接返回
    if (response.headers['content-disposition']) {
      return response;
    }
    // 这里需要根据不同的项目后端接口封装情况做适当调整
    if (res.error === 0) {
      return res;
    } else {
      message.error((res && res.msg) || '未知异常！');
      return Promise.reject(new Error((res && res.msg) || '未知异常！'));
    }
  },
  (error) => {
    if (axios.isCancel(error)) {
      console.log('Request canceled');
      return null;
    }
    if (error.response.data.errCode === '425') {
      message.error('登录失效，请重新登录！');
      router.push('/login');
    } else {
      message.error(error.response.data.msg || '未知异常！');
    }
    return Promise.reject(error);
  },
);

export default service;
